package com.share.controller.v1;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.share.constant.OAuthConstant;
import com.share.properties.GiteeProperties;
import com.share.properties.WeChatProperties;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

@Slf4j
@RestController
@RequestMapping("/user/v1")
public class OAuthController {

    private final GiteeProperties giteeProperties;
    private final WeChatProperties weChatProperties;

    @Autowired
    public OAuthController(GiteeProperties giteeProperties, WeChatProperties weChatProperties) {
        this.giteeProperties = giteeProperties;
        this.weChatProperties = weChatProperties;
    }

    /**
     * 微信服务器验证接口
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 随机字符串（仅验证时存在）
     * @return 验证成功返回echostr，失败返回错误信息
     */
    @RequestMapping("/weChatCheck")
    public String wxSignatureCheck(
            @RequestParam(value = "signature") String signature,
            @RequestParam(value = "timestamp") String timestamp,
            @RequestParam(value = "nonce") String nonce,
            @RequestParam(value = "echostr") String echostr
    ){
        // 1. 执行签名验证
        if (verifySignature(signature, timestamp, nonce)) {
            // 2. 验证成功原样返回echostr
            return echostr;
        }
        return "Invalid signature";
    }


    /**
     * 检验是否是微信返回的
     */
    private boolean verifySignature(String signature, String timestamp, String nonce) {
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = new String[]{weChatProperties.getToken(), timestamp, nonce};
        Arrays.sort(arr);

        // 2. 将三个参数字符串拼接成一个字符串
        String joinedStr = String.join("", arr);

        // 3. 对拼接后的字符串进行sha1加密
        String calculatedSignature = DigestUtils.sha1Hex(joinedStr);

        // 4. 将加密后的字符串与signature对比
        return calculatedSignature.equals(signature);
    }


    /**
     * 点击登录
     * 生成二维码
     */
    @GetMapping("/weChatLoginCode")
    public void wxLoginPage(HttpServletResponse response) throws Exception {
        //redirect_url是回调的地址 要转成UrlEncode格式
        String redirectUrl = URLEncoder.encode(weChatProperties.getRedirectUri(), StandardCharsets.UTF_8);
        //构造二维码链接地址
        String url = String.format(OAuthConstant.WX_CHECK,
                weChatProperties.getAppId(),
                redirectUrl,
                weChatProperties.getResponseType(),
                weChatProperties.getScope()
        );

        //生成二维码图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        QrCodeUtil.generate(url, 300, 300, "jpg", outputStream);

        //设置响应头
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        //将二维码图片写入响应
        try (ServletOutputStream out = response.getOutputStream()) {
            out.write(outputStream.toByteArray());
            out.flush();
        }
    }




}
